import logging
import os
import sys
import traceback
from logging import handlers

import app_config
from py.uitls import FileUtil


class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }  # 日志级别关系映射

    def __init__(self, filename, level='info', when='D', backCount=3):
        fmt = '%(asctime)s - File "%(pathname)s", line %(lineno)d - %(levelname)s - %(message)s'
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别
        sh = logging.StreamHandler()  # 往屏幕上输出
        sh.setFormatter(format_str)  # 设置屏幕上显示的格式
        # 往文件里写入#指定间隔时间自动生成文件的处理器
        th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount, encoding='utf-8')
        # 实例化TimedRotatingFileHandler
        # interval是时间间隔，backupCount是备份文件的个数，如果超过这个个数，就会自动删除，when是间隔的时间单位，单位有以下几种：
        th.setFormatter(format_str)  # 设置文件里写入的格式
        self.logger.addHandler(sh)  # 把对象加到logger里
        self.logger.addHandler(th)


path, file_name = os.path.split(sys.argv[0])
log_file = os.path.join(app_config.log_dir, os.path.splitext(file_name)[0] + ".dat")
FileUtil.create_file(log_file)
# FileUtil.save_file_text(log_file, "\n\n")
myLogger = Logger(log_file, level='debug').logger

if __name__ == '__main__':
    try:
        1 / 0
    except Exception as e:
        info = "asdds:" + traceback.format_exc()
        myLogger.info(info)
        myLogger.exception(e)
    myLogger.debug('debug')
    myLogger.info('info')
    myLogger.warning('警告')
    myLogger.error('报错')
    myLogger.critical('严重')
    Logger('error.log', level='error').logger.error('error')
